import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'

import TopCategory from '@/views/category/index.vue'
import SubCategory from '@/views/category/sub.vue'

import OrderIndex from '@/views/member/order/index.vue'
import { h } from 'vue'
const routes = [

  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },

  {
    path: '/login/callback',
    component: () => import('@/views/login/callback.vue')
  },

  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    children: [
      {
        path: '',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: 'category/:id',
        component: TopCategory
      },
      {
        path: 'category/sub/:id',
        component: SubCategory
      },
      { path: '/product/:id', component: () => import('@/views/goods/index.vue') },

      {
        path: '/cart',
        component: () => import('@/views/cart/index.vue')
      },

      {
        path: '/member/checkOut',
        component: () => import('@/views/member/pay/checkout.vue')
      },

      {
        path: '/member/pay',
        component: () => import('@/views/member/pay/index.vue')
      },

      {
        path: '/member',
        component: () => import('@/views/member/layout.vue'),

        children: [{
          path: '/member',
          component: () => import('@/views/member/home/index.vue')
        },

        {
          path: '/member/order/',
          // vue3.0 需要有嵌套关系才能模糊匹配
          component: { render: () => h(<RouterView/>) },
          children: [
            { path: '', component: OrderIndex },
            { path: ':id', component: () => import('@/views/member/order/orderDetail.vue') }
          ]
        }

        ]
      }

    ]
  }

]

// 创建路由实例
const router = createRouter({
  // hash模式
  history: createWebHashHistory(),
  routes,
  scrollBehavior () {
    return { left: 0, top: 0 }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})

export default router
